package com.weisw.polaris.admin.controller;

import java.util.List;

import com.weisw.polaris.admin.model.User;
import com.weisw.polaris.admin.service.UserService;
import com.weisw.polaris.admin.service.impl.UserServiceImpl;
import com.weisw.polaris.admin.util.PasswordUtils;
import com.weisw.polaris.core.http.HttpResult;
import com.weisw.polaris.core.page.PageRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


/**
 * 用户控制器
 * @author Louis
 * @date Jan 13, 2019
 */
@RestController
@RequestMapping("user")
public class UserController {

	@Autowired
	private UserServiceImpl userService;

	@PostMapping(value="/save")
	public HttpResult save(@RequestBody User record) {
		System.out.println(111);
		User user = userService.findById(record.getUserId());
		if(record.getPassword() != null) {
			String salt = PasswordUtils.getSalt();
			if(user == null) {
				// 新增用户
				if(userService.findByName(record.getUserName()) != null) {
					return HttpResult.error("用户名已存在!");
				}
				String password = PasswordUtils.encode(record.getPassword(), salt);
				record.setSalt(salt);
				record.setPassword(password);
			} else {
				// 修改用户, 且修改了密码
				if(!record.getPassword().equals(user.getPassword())) {
					String password = PasswordUtils.encode(record.getPassword(), salt);
					record.setSalt(salt);
					record.setPassword(password);
				}
			}
		}
		return HttpResult.ok(userService.save(record));
	}

	@PostMapping(value="/delete")
	public HttpResult delete(@RequestBody List<User> records) {
		return HttpResult.ok(userService.delete(records));
	}

	@GetMapping(value="/findByName")
	public HttpResult findByUserName(@RequestParam String name) {
		return HttpResult.ok(userService.findByName(name));
	}

	@PostMapping(value="/findPage")
	public HttpResult findPage(@RequestBody PageRequest pageRequest) {
		return HttpResult.ok(userService.findPage(pageRequest));
	}
	
}
